import 'package:async/async.dart';
import 'package:boss/provider/takeout_process_provider.dart';
import 'package:boss/ui/page/takeoutManagement/constant/takeout_status.dart';
import 'package:boss/ui/page/takeoutManagement/page/takeoutProcess/widget/reback_order_item.dart';
import 'package:boss/ui/page/takeoutManagement/page/takeoutProcess/widget/takeout_order_item.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class TakeoutProcessTabView extends StatefulWidget {
  final int status;

  const TakeoutProcessTabView({Key key, @required this.status}) : super(key: key);

  @override
  TakeoutProcessTabViewState createState() => TakeoutProcessTabViewState();
}

class TakeoutProcessTabViewState extends State<TakeoutProcessTabView> with AutomaticKeepAliveClientMixin {
  final GlobalKey<LoaderPullRefreshState> loaderPullRefreshKey = GlobalKey<LoaderPullRefreshState>();

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Consumer<TakeoutProcessProvider>(
      builder: (context, provider, _) {
        return LoaderPullRefresh(
          key: loaderPullRefreshKey,
          loadTask: loadTask,
          refreshTask: refreshTask,
          builder: (context) => ListView.builder(
            itemBuilder: (context, index) {
              var current = provider.data[widget.status][index];

              if (widget.status == TakeoutStatus.REBACK_ORDER) {
                return RebackOrderItem(
                  data: current,
                );
              }

              return TakeoutOrderItem(data: current);
            },
            itemCount: provider.data[widget.status].length,
          ),
        );
      },
    );
  }

  @override
  bool get wantKeepAlive => true;

  Future<Result<List>> loadTask() async {
    var provider = Provider.of<TakeoutProcessProvider>(
      context,
      listen: false,
    );

    if (!mounted) {
      return Result.value([]);
    }

    return provider.loadTakeoutOrderList(status: widget.status);
  }

  Future<Result<List>> refreshTask() async {
    var provider = Provider.of<TakeoutProcessProvider>(
      context,
      listen: false,
    );

    if (!mounted) {
      return Result.value([]);
    }

    return provider.refreshTakeoutOrderList(status: widget.status);
  }

  refresh() {
    loaderPullRefreshKey.currentState.refresh();
  }
}
